package cn.edu.zafu.bigdata.x.xiejunjie.fileoperations;

import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入文本
        System.out.print("请输入要保存的文本：");
        String content = scanner.nextLine();

        // 获取用户的学号
        System.out.print("请输入您的学号：");
        String studentId = scanner.nextLine();
        String fileName = "files/" + studentId + ".txt";

        // 将文本写入文件
        writeToFile(fileName, content);

        // 从文件中读取并显示内容
        readFromFile(fileName);

        scanner.close();
    }

    // 写入文件的方法
    private static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("文本已成功写入文件：" + fileName);
        } catch (IOException e) {
            System.err.println("写入文件时发生错误: " + e.getMessage());
        }
    }

    // 读取文件的方法
    private static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            System.out.println("文件内容：");
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
        }
    }
}
